package top.archiesean.api;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.google.common.net.HttpHeaders;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.archiesean.service.GenerateServer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author ArchieSean
 * @description 逆向工程接口
 * @date 2024-04-19
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("generate")
public class GenerateApi {

    private final GenerateServer generateServer;

    /**
     * 根据表名称逆向生成
     *
     * @param response  resp
     * @param tableName tableName
     * @return
     */
    @GetMapping("{tableName}")
    public String generateCode(HttpServletResponse response, @PathVariable("tableName") String tableName) {
        try {
            byte[] data = generateServer.getCode(tableName);
            response.reset();
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    String.format("attachment; filename=%s.zip", "generateCode"));
            response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
            response.setContentType("application/octet-stream; charset=UTF-8");
            IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
        } catch (IOException e) {
            log.error("生成代码出现异常", e);
        }
        return "success";
    }
}
